package com.digitalchina.lxnsy.fragment;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import androidx.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.apkfuns.logutils.LogUtils;
import com.digitalchina.lxnsy.R;
import com.digitalchina.lxnsy.activity.old.SetPayPasswordOneActivity;
import com.digitalchina.lxnsy.activity.old.WithdrawHistoryListActivity;
import com.digitalchina.lxnsy.base.BaseV4Fragment;
import com.digitalchina.lxnsy.constant.MSG;
import com.digitalchina.lxnsy.constant.URL;
import com.digitalchina.lxnsy.entity.CashLimitNewVO;
import com.digitalchina.lxnsy.entity.MyWalletVO;
import com.digitalchina.lxnsy.entity.UserInfo3rdPatyVO;
import com.digitalchina.lxnsy.toolkit.EncryptUtil;
import com.digitalchina.lxnsy.toolkit.FastJsonUtil;
import com.digitalchina.lxnsy.toolkit.GotoUtil;
import com.digitalchina.lxnsy.toolkit.OkHttpUtil;
import com.digitalchina.lxnsy.toolkit.StringUtil;
import com.digitalchina.lxnsy.widget.EditTextWithClear;
import com.digitalchina.lxnsy.xml.UserXML;
import com.lzy.okhttputils.model.HttpParams;
import com.mock.alipay.Callback;
import com.mock.alipay.PasswordKeypad;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * ================================================
 * 项目名称：BigData
 * 类描述：
 * 包名：com.digitalchina.bigdata.fragment
 * 创建人：郑皓
 * 创建时间：2018/10/8 17:51
 * 修改备注：
 * ================================================
 */
public class WithdrawAliPayFragment extends BaseV4Fragment {
    @Bind(R.id.et_name)
    EditTextWithClear etName;
    @Bind(R.id.et_account)
    EditTextWithClear etAccount;
    @Bind(R.id.et_money)
    EditText etMoney;
    @Bind(R.id.tv_all)
    TextView tvAll;
    @Bind(R.id.tv_avail_price)
    TextView tvAvailPrice;
    @Bind(R.id.tv_freeze_price)
    TextView tvFreezePrice;
    @Bind(R.id.bt_submit)
    Button btSubmit;
    @Bind(R.id.tv_info)
    TextView tvInfo;

    CashLimitNewVO cashLimitNewVO;

    private PasswordKeypad mKeypad;
    private String allPrice = "";
    private String mActualBal = "";
    private String mCanUseBal = "";
    private String mFreezeMoney = "";

    private String paymentPwd = "";

    @Override
    public View setRootView() {
        return inflate(R.layout.fragment_withdraw_alipay);
    }

    @Override
    public void initMember() {

        mActualBal = getArguments().getString("ActualBal");
        mCanUseBal = getArguments().getString("CanUseBal");
        mFreezeMoney = getArguments().getString("FreezeMoney");

        allPrice = mActualBal;
//        tvAvailPrice.setText("可用金额￥" + mActualBal);
//        tvFreezePrice.setText("暂不可提现金额￥" + mFreezeMoney);

        mKeypad = new PasswordKeypad();
        mKeypad.setPasswordCount(6);

        // 余额
        //BusinessWallet.getBalance(getActivity(), mHandler);
    }

    public void cashLimitNew(CashLimitNewVO vo) {
        cashLimitNewVO = vo;

        String s1 = String.format(tvAvailPrice.getText().toString(), mCanUseBal);
        tvAvailPrice.setText(s1);

        String s2 = String.format(tvFreezePrice.getText().toString(), vo.getMin(), vo.getMax());
        tvFreezePrice.setText(s2);

        String s3 = String.format(tvInfo.getText().toString(), vo.getTimes(), vo.getFreeAmount(), String.valueOf(Double.parseDouble(vo.getWxScale())*100));
        tvInfo.setText(s3);
    }

    public void set3rdUserInfo(UserInfo3rdPatyVO vo) {
        LogUtils.e(vo);

    }

    @Override
    public void addListener() {
        mKeypad.setCallback(new Callback() {
            @Override
            public void onForgetPassword() {
                GotoUtil.gotoActivity(getActivity(), SetPayPasswordOneActivity.class, true, "type", 1);
            }

            @Override
            public void onInputCompleted(CharSequence password) {
                paymentPwd = password.toString();
                cashLimitNew();
//                BusinessWallet.withdrawCashForAlipay(getActivity(), psw, etMoney.getText().toString(), etName.getText().toString(),
//                        etAccount.getText().toString(), mHandler);
            }

            @Override
            public void onPasswordCorrectly() {
                mKeypad.dismiss();
            }

            @Override
            public void onCancel() {
                //todo:做一些埋点类的需求
            }
        });
    }

    @Override
    public void setHandler() {
        mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);


                switch (msg.what) {
                    case MSG.MSG_WITHDRAW_CASH_SUCCESS:
                        showToast("提现申请成功");
                        mKeypad.setPasswordState(true);
                        break;
                    case MSG.MSG_WITHDRAW_CASH_FIELD:
                        showToast(msg.obj.toString());
                        mKeypad.setPasswordState(false, msg.obj.toString());
                        break;
                    case MSG.MSG_GET_BALANCE_SUCCESS: // 余额
                        MyWalletVO myWalletVO = FastJsonUtil.getBean(msg.obj.toString(), "", MyWalletVO.class);

                        /**
                         * actualBal    余额
                         * freezeMoney 总共冻结保障金(忽略）
                         * canUseBal  可用余额
                         */


                        if (myWalletVO != null) {
                            allPrice = myWalletVO.getActualBal();
                            tvAvailPrice.setText("可用金额￥" + myWalletVO.getActualBal());
                            tvFreezePrice.setText("暂不可提现金额￥" + myWalletVO.getFreezeMoney());
                        }
                        break;
                    case MSG.MSG_GET_BALANCE_FIELD:
                        showToast(msg.obj.toString());
                        break;

                    case MSG_S_0:
                        mKeypad.dismiss();
                        new MaterialDialog.Builder(getActivity())
                                .title("提示")
                                .content("提现申请成功")
                                .positiveText("确定")
                                .onPositive(new MaterialDialog.SingleButtonCallback() {
                                    @Override
                                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                                        getActivity().finish();
                                        GotoUtil.gotoActivity(getActivity(), WithdrawHistoryListActivity.class);
                                    }
                                })
                                .show();
                        break;
                    case MSG_F_0:
                        mKeypad.setPasswordState(false, msg.obj.toString());
                        showToast(msg.obj.toString());
                        break;
                }
            }
        };
    }

    @Override
    public void callBack(Object object) {

    }

    @Override
    public void rightOnClick() {

    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        // TODO: inflate a fragment view
        View rootView = super.onCreateView(inflater, container, savedInstanceState);
        ButterKnife.bind(this, rootView);
        return rootView;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.tv_all, R.id.bt_submit})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_all:
                if (StringUtil.isStrEmpty(allPrice)) {
                    showToast("余额获取失败，请重试。");
                } else {
                    etMoney.setText(allPrice);
                }
                break;
            case R.id.bt_submit:
                showPassword();
                break;
        }
    }

    private void showPassword() {

        if (StringUtil.isStrEmpty(etName.getText().toString())) {
            showToast("请输入支付宝姓名");
            return;
        }

        if (StringUtil.isStrEmpty(etAccount.getText().toString())) {
            showToast("请输入支付宝帐号");
            return;
        }

        if (StringUtil.isStrEmpty(etMoney.getText().toString())) {
            showToast("请输入提取金额");
            return;
        }
        mKeypad.show(getActivity().getSupportFragmentManager(), "PasswordKeypad");
    }

    //提现
    public void cashLimitNew() {
        HttpParams params = new HttpParams();

        params.put("userAccId", UserXML.getUserId(getActivity()));
        params.put("paymentPwd", EncryptUtil.SHA1(paymentPwd));
        params.put("withdrawWay", "1");//提现方式 银行卡 0 支付宝 1 微信 2
        params.put("payAmt", etMoney.getText().toString());
        params.put("accountNumber", etAccount.getText().toString());//支付宝账号
        params.put("userName", etName.getText().toString());//支付宝姓名


        OkHttpUtil.post(getActivity(), URL.URL_WITHDRAW_CASH_NEW, "请稍候...", params, mHandler,
                MSG_S_0, MSG_F_0);
    }
}
